﻿using UnityEngine;
using System.Collections;
using Mono.Data;
using Mono.Data.Sqlite;
using Assets.Scripts;
using System;


public class CharacterControllerScript : MonoBehaviour
{

    #region Fiends
    public float maxSpeed = 0.0f; // speed
    private bool isFacingRight = true; // pers orientation
    private Animator anim;
    private bool grounded = false;
    public Transform groundCheck;
    private float groundRadius = 0.2f;
    public LayerMask whatIsGround;
    public float jumpForce = 700f;
    private float moveTouch = 0.0f;
    private bool moving = false;
    #endregion

    #region Start Section
    void Start()
    {
        anim = GetComponent<Animator>();
    }
    #endregion

    #region Update Section
    void FixedUpdate()
    {

       // grounded = false;
        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool("Ground", grounded);
        anim.SetFloat("vSpeed", rigidbody2D.velocity.y);

        if (!grounded)
            return;

        anim.SetFloat("Speed", Mathf.Abs(moveTouch));

        rigidbody2D.velocity = new Vector2(moveTouch * maxSpeed, rigidbody2D.velocity.y);
        if (moveTouch > 0 && !isFacingRight)
            Flip();
        else if (moveTouch < 0 && isFacingRight)
            Flip();
    }

    void Update()
    {

        switch (Application.platform)
        {
            case RuntimePlatform.Android:
                TouchToAndroidPlatform();
                break;
            case RuntimePlatform.WindowsEditor:
                TouchToWindowsPlatform();
                break;
            default:
                Debug.Log("Platform dont assigment " + Application.platform);
                break;
        }
    }

    #endregion

    #region Custom Functions
    void Flip()
    {
        isFacingRight = !isFacingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
    void CheckTouch(Vector3 pos, string phase)
    {
        Vector3 wp = Camera.main.ScreenToWorldPoint(pos);
        Vector2 touchPos = new Vector2(wp.x, wp.y);
        Collider2D hit = Physics2D.OverlapPoint(touchPos);
        //test = hit.gameObject.name;
        //hit.gameObject.name == "LeftButton"

        // start moving {
        if (hit && phase == "began")
        {
            //using (DatabaseManager manager = new DatabaseManager("URI=file:" + Application.dataPath + "/Database/main"))
            //{
            //    manager.ConnectToDatabase();
            //    if (manager.CreateTable<Tested>())
            //        Debug.Log("Table created!");
            //   else
            //       Debug.Log("Table is in DB or Smth. Wrong");
                switch (hit.gameObject.name)
                {
                    case "LeftButton":
                        moveTouch = -1f;
                        //moveSpeed = new Vector2(-3f, 0f);
                        //var pers = new Tested() {Firstname = "Dima", Lastname = "Pavlenko" + moveTouch * 10, Date = DateTime.UtcNow.ToShortDateString() };
                        //manager.InsertRecord<Tested>(pers);
                        //manager.DropTable<Tested>();
                        moving = true;
                        break;
                    case "RightButton":
                        moveTouch = 1f;
                        //moveSpeed = new Vector2(3f, 0f);
                        moving = true;
                        // var pers = new Tested(){Id = 1, Firstname = "Dima", Lastname = "Pavlenko", Date = DateTime.UtcNow.ToShortDateString()};
                        //var pers1 = new Tested() { Id = 2, Firstname = "Sasha", Lastname = "Dykov", Date = DateTime.UtcNow.ToShortDateString() };

                       
                        //// manager.CreateTable<Tested>();
                        ////  manager.InsertRecord<Tested>(pers);
                        ////  manager.InsertRecord<Tested>(pers1);
                        //var s = manager.ReadAll<Tested>();
                        //var t = manager.ReadByFieldName<Tested>("Id", 11);
                        //var t1 = manager.ReadByFieldName<Tested>("Firstname", "Gena");
                        //var t12 = manager.ReadByFieldName<Tested>("Lastname", "Pavlenko");
                        ////var res1 = manager.DeleteRecordById<Tested>(5);
                        

                        ////   manager.CreateTable<FirstTable>();
                        //// var ids = manager.ReadAllIDS("test");
                        // foreach (var it in s)
                        //   Debug.Log(string.Format("{0} --- {1} --- {2} --- {3}\n",it.Id,it.Lastname,it.Firstname,it.Date));
                        
                        break;
                    case "JumpButton":
                        if (grounded)
                        {
                            anim.SetBool("Ground", false);
                            rigidbody2D.AddForce(new Vector2(0, jumpForce));
                        }
                        // player.rigidbody2D.AddForce(new Vector2(0f, jumpForce)); //Add jump force to hero
                        break;
                }
            }

        //}
        // }

        // end movind
        if (phase == "ended")
        {
            //player.rigidbody2D.velocity = Vector2.zero;
            moving = false;
            moveTouch = 0;
        }
    }
    #endregion

    #region Touches Handlers Region
    private void TouchToWindowsPlatform()
    {
        if (Input.GetMouseButtonDown(0))
            CheckTouch(Input.mousePosition, "began");

        if (Input.GetMouseButtonUp(0))
            CheckTouch(Input.mousePosition, "ended");   
    }

    private void TouchToAndroidPlatform()
    {
        for (int i = 0; i < Input.touchCount; i++)
        {
            if (Input.GetTouch(i).phase == TouchPhase.Began)
                CheckTouch(Input.GetTouch(i).position, "began");
            else if (Input.GetTouch(i).phase == TouchPhase.Ended)
                CheckTouch(Input.GetTouch(i).position, "ended");
        }
    }
    #endregion

    public class Tested
    {
        [PrimaryKeyField(true)]
        public int Id { get;set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Date { get; set; }

        public Tested()
        {

        }
    }
}
